package xyz.lwm.lazycat.netpipe;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import xyz.lwm.lazycat.annotation.Inject;
import xyz.lwm.lazycat.beans.AppRunner;
import xyz.lwm.lazycat.beans.Application;
import xyz.lwm.lazycat.netpipe.common.endec.GzipCodec;
import xyz.lwm.lazycat.netpipe.common.endec.MessageCodec;
import xyz.lwm.lazycat.netpipe.common.serial.SerialType;
import xyz.lwm.lazycat.netpipe.common.serial.Serialization;
import xyz.lwm.lazycat.netpipe.common.serial.SerializationFactory;
import xyz.lwm.lazycat.netpipe.setting.NetpipeClientSetting;

import javax.annotation.PreDestroy;

/**
 * Netpipe Client
 *
 * @author lwm
 */
@Slf4j
public class NetpipeClient implements AppRunner {

    public static void main(String[] args) {
        Application.run();
    }

    private final Bootstrap bootstrap = new Bootstrap();

    private final NioEventLoopGroup clientWorkerGroup = new NioEventLoopGroup();

    private final Serialization serialization = SerializationFactory.getSerialization(SerialType.PROTOSTUFF);

    @Inject
    private NetpipeClientSetting clientSetting;

    @Override
    public void run(String[] args) {
        bootstrap.group(clientWorkerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new GzipCodec());
                        //固定帧长解码器
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                        ch.pipeline().addLast(new LengthFieldPrepender(4));
                        ch.pipeline().addLast(new ChunkedWriteHandler());
                        //自定义协议编解码器
                        ch.pipeline().addLast(new MessageCodec(serialization));
                    }
                }).connect(clientSetting.getServerIp(), clientSetting.getServerPort())
                .addListener(future -> {
                    if (future.isSuccess()) {
                        log.info("Netpipe Client started successfully, connecting to " + clientSetting.getServerIp() + ":" + clientSetting.getServerPort());
                    } else {
                        log.error("Netpipe Client start failed, server ip: {}, server port:{}, reason:{}.",
                                clientSetting.getServerIp(), clientSetting.getServerPort(), future.cause().getMessage());
                    }
                });
    }

    @PreDestroy
    public void stop() {
        clientWorkerGroup.shutdownGracefully();
    }

}
